//把配置项单独处理

let server_url=' ';//请求地址
let token = ' ';  //凭证
server_url = process.env.NODE_ENV === 'development' ? 'https://test.ven6.com' : 'http://gt163.cn:15103' ; //环境配置

function checkStatus(response) {
	const { statusCode, data } = response;
	if (statusCode >= 200 && statusCode < 300) {
		return response;
	}
	
	const error = new Error(data.message);
	error.response = response;
	
	throw error;
}

function request(method = "GET", url = '', data = {}, header = {}, loading = true) {
	if (url === "") return;
	token = uni.getStorageSync('token');
	loading && uni.showLoading({
		title: '加载中',
		mask: true
	})
	
	return uni.request({
		method,
		data,
		url: `${server_url}${url}`,
		header:{
			...header,
			token
		}
	})
	.then(res => checkStatus(res[1]))
	.then(res => {
		console.log('res:', res);
		loading && uni.hideLoading();
		const { data, status, message }  = res.data;
		
		if (status === 200) {
			return data;
		}
		
		uni.showToast({
			icon: 'none',
			duration: 3000,
			title: message || '网络异常, 请稍后重试'
		})
		
		return res;
	})
	.catch(err => {
		loading && uni.hideLoading();
		return err
	})
}

export default request;